package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedis;

    @RequestMapping("/send4Order")
    public Result send4Order(String telephone) {
        //获取验证码
        try {
            Integer validCode = ValidateCodeUtils.generateValidateCode(4);
            SMSUtils.sendMessage(SMSUtils.VALIDATE_CODE,telephone,validCode.toString());
            //如果发送成功
            System.out.println("发送的手机验证码为："+validCode);
            jedis.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER,5*60,validCode.toString());
            jedis.close();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    @RequestMapping("/check")
    public Result check(String validateCode,String telephone) {
        //查询redis中
        String key = telephone+RedisMessageConstant.SENDTYPE_ORDER;
        String valid = jedis.getResource().get(key);
        jedis.close();
        if(valid != null && valid.equals(validateCode)) {
            return new Result(true,MessageConstant.VALIDATECODE_TRUE);
        }
        return new Result(false,MessageConstant.VALIDATECODE_ERROR);
    }

    @RequestMapping("/send4Login")
    public Result send4Login(String telephone) {
        //获取验证码
        try {
            Integer validCode = ValidateCodeUtils.generateValidateCode(6);
            SMSUtils.sendMessage(SMSUtils.VALIDATE_CODE,telephone,validCode.toString());
            //如果发送成功
            System.out.println("发送的手机验证码为："+validCode);
            jedis.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_LOGIN,5*60,validCode.toString());
            jedis.close();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
